package com.hwtx.form.domain.handle.core;

import com.fasterxml.jackson.databind.JsonNode;
import com.hwtx.form.annotation.FormId;
import com.hwtx.form.domain.FormConstants;
import com.hwtx.form.domain.def.FormDef;
import com.hwtx.form.domain.handle.FormDefHandle;
import com.hwtx.form.domain.handle.FormI18nHandle;
import com.hwtx.form.domain.handle.FormPermissionFilter;
import com.hwtx.form.domain.handle.i18n.I18nConfig;
import com.hwtx.form.domain.repo.RoleUserRepo;
import io.geekidea.boot.auth.cache.LoginCache;
import io.geekidea.boot.system.enums.SysMenuType;
import jakarta.annotation.Resource;
import org.springframework.context.MessageSource;

import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import static com.hwtx.form.domain.FormConstants.DEFAULT_FORM_ID;

@FormId(DEFAULT_FORM_ID)
public class DefaultFormDefHandle implements FormDefHandle {

    @Resource
    private RoleUserRepo roleUserRepo;
    @Resource
    private MessageSource messageSource;
    @Resource
    private I18nConfig i18nConfig;

    @Override
    public void handleDefContent(FormDef formDef, JsonNode root, Map<String, String[]> formDefQuery) {

        if (!LoginCache.get().isAdmin() && formDef.isAuth()) {
            List<String> resourceCodes = roleUserRepo.getResourceCodeByUserId(LoginCache.get().getUserId(), Collections.singletonList(SysMenuType.FUN_PERMISSION.getCode()));
            FormPermissionFilter.permissionFilter(root, resourceCodes);
        }
        String[] localeStr = formDefQuery.get(FormConstants.LOCALE_PARAM);
        Locale locale = Locale.getDefault();
        if (localeStr != null && localeStr.length == 1) {
            locale = Locale.forLanguageTag(localeStr[0]);
        }
        FormI18nHandle.handle(root, messageSource, i18nConfig.getGroup(), locale);
    }
}
